<template>
	<view>
		<!-- #ifdef APP-PLUS -->
		<view>
			<uni-nav-bar left-icon="arrowleft" @clickLeft="back" title="确认支付" :statusBar='true' :fixed="true"></uni-nav-bar>
		</view>
		<!-- #endif -->
		<view class="novippay">
			<view class="novippay-content">
				<text class="novippay-content-name">收款商家：{{ store.storeName }}</text>
				<text class="novippay-content-line"></text>
				<view class="novippay-content-money">
					小票金额：<view @click="onCLickShowKeyWord" class="novippay-content-money-input">{{ yourMoney }}</view>
				</view>
				<view class="novippay-content-select">
					<!-- 在你是游客的情况下 -->
					<view @click="onClickSelectJHHY" v-if="member.isPlus === '0'" class="novippay-content-select-left">
						<image :src="jhhy === true ? '../../static/novippay/select-vip.png': '../../static/novippay/no-select.png'" class="novippay-content-select-left-img"></image>
						<text class="novippay-content-select-left-txt">注册会员+1元</text>
					</view>
					<view @click="onClickSelectJHPLUSHY" v-if="member.isPlus === '0'" class="novippay-content-select-right">
						<image :src="jhplushy === true ? '../../static/novippay/select-plusvip.png': '../../static/novippay/no-select.png'"
						 class="novippay-content-select-right-img"></image>
						<text class="novippay-content-select-right-txt">注册plus会员+199元</text>
					</view>
					<!-- 在你是会员的情况下 -->
					<!-- <view @click="onClickSYMD" v-if="(member.isPlus === '1') || (member.isPlus === '2')" class="novippay-content-select-right">
						<image :src="symd === true ? '../../static/novippay/select-plusvip.png': '../../static/novippay/no-select.png'"
						 class="novippay-content-select-right-img"></image>
						<text class="novippay-content-select-right-txt">使用码豆</text>
					</view> -->
				</view>
				<text class="novippay-content-line"></text>
				<view class="novippay-content-info" v-if='(store.rate) && (store.rate !== undefined) && (store.rate.length)'>
					<text v-if="(member.isPlus === '0') && (jhhy === false) && (jhplushy === false)" class="novippay-content-info-txt-zk zk">折扣：无折扣</text>
					<text v-if="(member.isPlus === '0') && (jhhy === true) && (jhplushy === false)" class="novippay-content-info-txt-zk zk">折扣：{{ Math.floor(JSON.parse(store.rate).vip1 * 100) / 10 }}折</text>
					<text v-if="(member.isPlus === '0') && (jhhy === false) && (jhplushy === true)" class="novippay-content-info-txt-zk zk">折扣：{{ Math.floor(JSON.parse(store.rate).vip2 * 100) / 10 }}折</text>
					<text v-if="(member.isPlus === '1')" class="novippay-content-info-txt-zk zk">会员折扣：{{ Math.floor(JSON.parse(store.rate).vip1 * 100) / 10 }}折</text>
					<text v-if="(member.isPlus === '2')" class="novippay-content-info-txt-zk zk plus">PLUS会员折扣：{{ Math.floor(JSON.parse(store.rate).vip2 * 100) / 10 }}折</text>
					<text v-if="yourMoney" class="novippay-content-info-txt-zk je">节省金额：¥{{ computedJSMoney }}</text>
					<!-- <text v-if="(member.isPlus === '0') && (jhhy === true)" class="novippay-content-info-txt-zk hy">激活会员：¥1.00</text> -->
					<!-- <text v-if="(member.isPlus === '0') && (jhplushy === true)" class="novippay-content-info-txt-zk hy">激活plus会员：¥199.00</text> -->
					<text v-if="yourMoney" class="novippay-content-info-txt-zk sf">实付金额：¥{{ shifujine }}</text>
				</view>
			</view>
			<view v-if="yourMoney" class="novippay-btn">
				<button v-if="member.isPlus === '0'" @click="pay" class="novippay-btn-wrap">¥{{ shifujine }} 成为会员并结帐</button>
			</view>
			
			<keyboard-package ref="number" 
			:shifujine="shifujine" 
			 @onInput="onInput" 
			 @onDelete="onDelete"
			 @onConfirm="onConfirm" 
			 :disableDot="true" 
			 :safeAreaInsetBottom='true'
			 :yourMoney="yourMoney"
			 :member="member"/>
		</view>
	</view>
</template>
<script> 
	import { config } from '@/utils/config.js';
	import BigNumber from '@/utils/bignumber.min.js';
	import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue';
	import keyboardPackage from "@/components/keyboard-package/keyboard-package.vue";
	// #ifdef H5
	const jweixin = require('../../utils/jweixin-module.js');
	// #endif
	export default {
		components: {
			uniNavBar,
			keyboardPackage,
		},
		computed: {
			// 节省的金额
			computedJSMoney() {
				if (this.member.isPlus === '2') {
					return ((new BigNumber(1).minus(JSON.parse(this.store.rate).vip2)).multipliedBy(new BigNumber(this.yourMoney))).toFixed(2, 2)
				} else if (this.member.isPlus === '1') {
					return ((new BigNumber(1).minus(JSON.parse(this.store.rate).vip1)).multipliedBy(new BigNumber(this.yourMoney))).toFixed(2, 2)
				} else {
					if ((this.jhhy === false) && (this.jhplushy === false)) {
						return 0
					} else if ((this.jhhy === true) && (this.jhplushy === false)) {
						return ((new BigNumber(1).minus(JSON.parse(this.store .rate).vip1)).multipliedBy(new BigNumber(this.yourMoney))).toFixed(2, 2)
					} else if ((this.jhhy === false) && (this.jhplushy === true)) {
						return ((new BigNumber(1).minus(JSON.parse(this.store.rate).vip2)).multipliedBy(new BigNumber(this.yourMoney))).toFixed(2, 2)
					}
				}
			},
			// 实付
			shifujine() {
				if (this.member.isPlus === '2') {
					return new BigNumber(JSON.parse(this.store.rate).vip2).multipliedBy(new BigNumber(this.yourMoney)).toFixed(2, 2)
				} else if (this.member.isPlus === '1') {
					return new BigNumber(JSON.parse(this.store.rate).vip1).multipliedBy(new BigNumber(this.yourMoney)).toFixed(2, 2)
				} else {
					if ((this.jhhy === false) && (this.jhplushy === false)) { // 啥都没点击，既不开通会员，也不开通svip会员
						return new BigNumber(this.yourMoney).toFixed(2, 2)
					} else if ((this.jhhy === true) && (this.jhplushy === false)) { // 开通普通会员：vip1折扣+1块
						return new BigNumber(JSON.parse(this.store.rate).vip1).multipliedBy(new BigNumber(this.yourMoney)).plus(new BigNumber(1)).toFixed(2, 2)
					} else if ((this.jhhy === false) && (this.jhplushy === true)) { // 开通普通会员：vip2折扣+199块
						return new BigNumber(JSON.parse(this.store.rate).vip2).multipliedBy(new BigNumber(this.yourMoney)).plus(new BigNumber(199)).toFixed(2, 2)
					}
				}
			}
		},
		data() {
			return {
				storeId: '',
				member: {},
				ordersId: '',
				store: {},
				jhhy: true, // 激活会员
				jhplushy: false, // 激活plus
				symd: false, // 使用码豆
				yourMoney: '', // 用户输入的金额
				yourArrMoney: ''
			}
		},
		onShow() {
			// 隐藏软键盘，2020-4-19 17:35:20 新增
			uni.hideKeyboard()
		},
		onReady() {
			// 隐藏软键盘，2020-4-19 17:35:20 新增
			uni.hideKeyboard()
			this.$nextTick(() => {
				this.$refs.number.open();
			})
		},
		onLoad(e) {
			// 隐藏软键盘，2020-4-19 17:35:20 新增
			uni.hideKeyboard()
			if (e && e.storeId) {
				this.storeId = e.storeId
				this.$nextTick(() => {
					// #ifdef APP-PLUS || MP
					this._readyToPay(this.storeId, uni.getStorageSync('memberId'))
					// #endif
					// #ifdef H5
					this._beginSetCheck()
					// #endif	
				})
			}
		},
		methods: {
			onInput(val) {
				if(val === '.'){
					if (this.yourMoney.indexOf('.') > -1) {
						return false
					}
					if (!this.yourMoney) {
						val = '0.'
					}
				}
				
				this.yourMoney = this.yourMoney + val
			},
			onDelete() {
				if (!this.yourMoney) {
					return false
				}
				let newArr = this.yourMoney.split('')
				let newLength = newArr.length
				newArr.length = newLength - 1
				this.yourMoney = newArr.join('')
			},
			onConfirm() {
				this.$refs.number.close();
				console.log(this.yourMoney)
			},
			onCLickShowKeyWord(){
				this.$refs.number.open();
			},
			// 判断公众号截取code
			getUrlParam(name) {
				let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
				let r = window.location.search.substr(1).match(reg);
				if (r != null) {
					return unescape(r[2]);
				}
				return null;
			},
			_beginSetCheck() {
				const token = uni.getStorageSync('token')
				if (token) {
					uni.request({
						url: `${config.api_base_url}member/member/findByToken`,
						header: {
							'AUTH': 'ROBOT ' + uni.getStorageSync('token'),
						},
						success: ((res) => {
							let { status, data } = res.data
							if (status.flag === true) {
								// 有效的
								// 做有token的事情，其实就是：
								// 1、请求本页面信息；
								// 2、设置支付环境
								this._readyToPay(this.storeId, uni.getStorageSync('memberId'))
								this._beginSetConfig()
							} else {
								// 无效的
								uni.removeStorageSync('role')
								uni.removeStorageSync('memberId')
								uni.removeStorageSync('token')
								uni.removeStorageSync('openId')
								this._beginSetCheck()
							}
						}),
						fail: (() => {
							uni.showToast({
								title: '网络异常, 暂时不能查询',
								icon: 'none'
							})
						}),
						complete: (() => {
							uni.hideLoading()
						})
					});
				} else {
					// 做没有token的事情
					// 去授权弹窗，拿到code、再拿到openId，再去请求access_token，再去最后一次跟后端保存信息
					if (!this.getUrlParam('code')) {
						let url = window.location.href
						let new_url = encodeURIComponent(url)
						window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6246e0503023027f&redirect_uri=${new_url}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`
					} else if (this.getUrlParam('code')) {
						uni.showLoading({
							title: '正在登录中'
						})
						const code = this.getUrlParam('code')
						uni.request({
							url: `${config.api_base_url}member/member/openid/${code}`,
							header: {
								'Content-Type': 'application/json'
							},
							success: ((res) => {
								let { status, data } = res.data
								if (status.flag === true) {
									const openid = data.openid
									uni.setStorageSync('openId', openid)
									// 拿access_token
									uni.request({
										url: `${config.api_base_url}member/member/getAccessToken`,
										success: ((res_t) => {
											let { status, data } = res_t.data
											if (status.flag === true) {
												const access_token = data.access_token
												uni.request({
													url: `${config.api_base_url}member/member/getWeChatInfo`,
													method: 'POST',
													data: {
														access_token: access_token,
														open_id: openid
													},
													success: ((res_ac) => {
														let { status, data } = res_ac.data
														if (status.flag === true) {
															uni.setStorageSync('role', data.role)
															uni.setStorageSync('token', data.token)
															uni.setStorageSync('memberId', data.memberId)
															this._readyToPay(this.storeId, data.memberId)
															this._beginSetConfig()
														} else {
															uni.showToast({
																icon: 'none',
																title: status.msg
															})
														}
													}),
													fail: (() => {
														uni.showToast({
															icon: 'none',
															title: '请求失败, 网络异常'
														})
													}),
													complete: (() => {
														uni.hideLoading()
													})
												})
											}
										})
									})
								}
							})
						})
					}
				}
			},
			// 去设置本页面的路径，支付
			_beginSetConfig() {
				uni.request({
					url: `${config.api_base_url}orders/pay/config`,
					method: 'POST',
					data: {
						url: location.href
					},
					success: ((res) => {
						let { status, data } = res.data
						if (status.flag === true) {
							jweixin.config({
								debug: false,
								appId: data.appid, // 必填，公众号的唯一标识
								timestamp: data.timestamp, // 必填，生成签名的时间戳
								nonceStr: data.nonceStr, // 必填，生成签名的随机串
								signature: data.signature, // 必填，签名，见附录1
								jsApiList: [
									'checkJsApi',
									'chooseWXPay'
								]
							});
							jweixin.ready(() => {
								jweixin.checkJsApi({
									jsApiList: ['chooseWXPay'],
									success: ((res) => {
										console.log(res)
									})
								});
							})
							jweixin.error((err) => {
								console.log(err)
							})
						}
					})
				})
			},
			back() {
				uni.navigateBack({})
			},
			onClickSYMD() {
				this.symd = !this.symd
			},
			onClickSelectJHHY() {
				this.jhhy = true
				this.jhplushy = false
			},
			onClickSelectJHPLUSHY() {
				this.jhhy = false
				this.jhplushy = true
			},
			_readyToPay(id, memberId) {
				uni.showLoading({})
				const newId = id
				let _url = `${config.api_base_url}orders/orders/preOrders/${newId}`
				uni.request({
					url: _url,
					method: 'POST',
					header: {
						'AUTH': 'ROBOT ' + uni.getStorageSync('token'),
						'Content-Type': 'application/json'
					},
					data: {
						memberId: memberId
					},
					success: ((res) => {
						let { status, data } = res.data
						if (status.flag === true) {
							this.member = data.member
							this.ordersId = data.ordersId
							this.store = data.store
							console.log(this.store)
							console.log(this.store.storeName)
						} else {
							this.member = {}
							this.ordersId = ''
							this.store = {}
						}
					}),
					fail: (() => {
						uni.showToast({
							icon: 'none',
							title: '请求失败, 网络异常'
						})
					}),
					complete: (() => {
						uni.hideLoading()
					})
				})
			},
		}
	}
</script>
<style>
	page {
		background-color: #F6F6F6;
	}
</style>
<style>
	.novippay {
		width: 100%;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		padding-top: 18rpx;
		padding-right: 14rpx;
		padding-left: 16rpx;
	}

	.novippay-content {
		width: 100%;
		background-color: #FFFFFF;
		border-radius: 20rpx;
		box-sizing: border-box;
		padding-top: 42rpx;
		padding-right: 20rpx;
		padding-bottom: 42rpx;
		padding-left: 26rpx;
		display: flex;
		flex-direction: column;
	}

	.novippay-content-name {
		font-size: 36rpx;
		font-weight: 600;
		color: rgba(0, 0, 0, 0.85);
		line-height: 50rpx;
	}

	.novippay-content-line {
		width: 100%;
		height: 2rpx;
		background-color: #EEEEEE;
		margin-top: 24rpx;
	}

	.novippay-content-info {
		display: flex;
		flex-direction: column;
		margin-top: 22rpx;
	}

	.novippay-content-info-txt-zk {
		font-size: 32rpx;
		font-weight: 500;
		line-height: 40rpx;
		margin-bottom: 12rpx;
	}

	.novippay-content-info-txt-zk:last-child {
		margin-bottom: 0;
	}

	.zk {
		color: #1E92E8;
	}

	.je {
		color: #F02230;
	}

	.hy {
		color: #FA6400;
	}

	.sf {
		color: #000000;
	}

	.plus {
		color: #F02230;
	}

	.novippay-content-money {
		width: 100%;
		height: 102rpx;
		margin-top: 18rpx;
		display: flex;
		align-items: center;
		box-sizing: border-box;
		padding-left: 22rpx;
		font-size: 28rpx;
	}

	.novippay-content-money-input {
		flex: 1;
		height: 100%;
		line-height: 102rpx;
		font-size: 40rpx;
		box-sizing: border-box;
		padding-left: 5rpx;
		font-size: 28rpx;
		color: #000;
		background-color: #F8F8F8;
		border-radius: 8rpx;
	}

	.novippay-content-select {
		display: flex;
		align-items: center;
		margin-top: 38rpx;
		box-sizing: border-box;
		padding-left: 16rpx;
	}

	.novippay-content-select-left {
		display: flex;
		align-items: center;
		margin-right: 100rpx;
	}

	.novippay-content-select-left-img {
		width: 33rpx;
		height: 33rpx;
		border-radius: 50%;
		margin-right: 22rpx;
	}

	.novippay-content-select-left-txt {
		font-size: 26rpx;
		font-weight: 400;
		color: #1E92E8;
	}

	.novippay-content-select-right {
		display: flex;
		align-items: center;
	}

	.novippay-content-select-right-img {
		width: 33rpx;
		height: 33rpx;
		border-radius: 50%;
		margin-right: 22rpx;
	}

	.novippay-content-select-right-txt {
		font-size: 26rpx;
		font-weight: 400;
	}

	.novippay-btn {
		width: 100%;
		height: 82rpx;
		margin-top: 32rpx;
		box-sizing: border-box;
		padding-left: 12rpx;
		padding-right: 12rpx;
	}

	.novippay-btn-wrap {
		width: 100%;
		height: 100%;
		background-color: #F02230;
		border-radius: 14rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 32rpx;
		color: #fff;
	}
</style>
